package com.leon.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.leon.admin.feign.ArticleFeign;
import com.leon.admin.feign.WemediaFeign;
import com.leon.admin.mapper.AdChannelMapper;
import com.leon.admin.mapper.AdSensitiveMapper;
import com.leon.admin.service.WemediaNewsAutoScanService;
import com.leon.common.aliyun.GreeTextScan;
import com.leon.common.aliyun.GreenImageScan;
import com.leon.common.fastdfs.FastDFSClient;
import com.leon.model.admin.dtos.NewsAuthDto;
import com.leon.model.admin.pojos.AdChannel;
import com.leon.model.article.pojos.ApArticle;
import com.leon.model.article.pojos.ApArticleConfig;
import com.leon.model.article.pojos.ApArticleContent;
import com.leon.model.article.pojos.ApAuthor;
import com.leon.model.common.dtos.PageResponseResult;
import com.leon.model.common.dtos.ResponseResult;
import com.leon.model.common.enums.AppHttpCodeEnum;
import com.leon.model.media.pojos.WmNews;
import com.leon.model.media.pojos.WmUser;
import com.leon.model.media.vo.WmNewsVo;
import com.leon.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @description:
 * @program: leon-leadnews
 * @author: Leon
 * @date: 2021-03-17 18:55
 **/
@Service
@Slf4j
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private AdChannelMapper adChannelMapper;

    @Autowired
    private AdSensitiveMapper adSensitiveMapper;

    @Autowired
    private FastDFSClient fastDFSClient;

    @Value("${fdfs.url}")
    private String fileServerUrl;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private GreeTextScan greeTextScan;

    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {

        if (id == null) {
            log.error("当前审核Id为空");
            return;
        }
        //1.根据id查询自媒体文章信息
        WmNews wmNews = wemediaFeign.findById(id);
        if (wmNews == null){
            log.error("待审核的文章不存在，Id为:"+id);
            return;
        }
        //2.文章状态为4（人工审核通过）直接保存数据和创建索引
        if (wmNews.getStatus() == 4){
            //保存数据
            saveAppArticle(wmNews);
            return;
        }
        //3.文章状态为8  发布时间>当前时间 直接保存数据
        Date date = new Date();
        boolean flag = date.compareTo(wmNews.getPublishTime()) <= 0 ? true : false;
        if (wmNews.getStatus() == 0 || flag){
            //保存数据
            saveAppArticle(wmNews);
        }
        //4.文章状态为1，待审核
        if (wmNews.getStatus() == 1){
            //抽取文章内容中的纯文本和图片
            Map<String,Object> contentAndImagesResult = handleTextAndImages(wmNews);
            //4.1 文本审核
            boolean textScanBoolean =  handleTextScan((String) contentAndImagesResult.get("content"),wmNews);
            if (textScanBoolean) return;
            //4.2 图片审核
            boolean imagesScanBoolean =  handleImagesScan((List<String>) contentAndImagesResult.get("images"), wmNews);
            //4.3 自管理的敏感词审核
            if (imagesScanBoolean) return;
            boolean sensitiveScanBoolean = handleSensitive((String) contentAndImagesResult.get("content"), wmNews);
            if (sensitiveScanBoolean) return;
            //4.4 发布时间大于当前时间，
            if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()){
                //修改文章状态为8
                updateWmNews(wmNews,(short) 8,"审核通过，待发布");
                return;
            }
            //5.审核通过，修改自媒体文章状态为9  保存app端相关文章信息
            saveAppArticle(wmNews);
        }
    }

    /**
     * 敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;    
        // 查找敏感词集合
        List<String> allSensitive = adSensitiveMapper.findAllSensitive();
        // 初始化敏感词
        SensitiveWordUtil.initMap(allSensitive);
        // 文章内容自管理敏感词过滤
        Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(content);
        if (stringIntegerMap.size() > 0 ){
            log.error("敏感词没通过，包含了敏感词:"+stringIntegerMap);
            // 设置审核不通过
            updateWmNews(wmNews,(short) 2,"包含敏感词");
            flag = false;
        }
        return flag;
    }

    /**
     * 图片审核
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        if (images == null){
            return true;
        }
        boolean flag = true;

        List<byte[]> imageList = new ArrayList<>();
        try {
            for (String image : images) {
                String imageName = image.replace(fileServerUrl, "");
                int index = imageName.indexOf("/");
                String groupName = imageName.substring(0, index);
                String imagePath = imageName.substring(index + 1);
                byte[] imageByte = fastDFSClient.download(groupName, imagePath);
                imageList.add(imageByte);
            }
            //阿里云图片审核
            Map map = greenImageScan.imageScan(imageList);
            //审核不通过
            if (!map.get("suggestion").equals("pass")) {
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    //修改自媒体文章的状态，并告知审核失败原因
                    updateWmNews(wmNews, (short) 2, "文章中图片有违规");
                    flag = false;
                }
// todo
                //人工审核
                if (map.get("suggestion").equals("review")) {
                    //修改自媒体文章的状态，并告知审核失败原因
                    updateWmNews(wmNews, (short) 3, "文章图片有不确定元素");
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }

        return flag;
    }

    /**
     * 文本审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        try{
            Map map = greeTextScan.greeTextScan(content);
            // 审核不通过
            if (!map.get("suggestion").equals("pass")){
                // 审核失败
                if (!map.get("suggestion").equals("block")){
                    // 修改自媒体文章的状态，并告知审核失败原因
                    updateWmNews(wmNews,(short)2,"文章中有敏感词汇");
                    flag = false;
                }
                // 人工审核
                if (map.get("suggestion").equals("review")){
                    // 修改自媒体文章的状态,并告知审核失败的原因
                    updateWmNews(wmNews, (short) 3, "文章内容中有不确定词汇");
                    flag = false;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 提取文章内容中的图片和文本
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //文章的内容
        String content = wmNews.getContent();

        //存储纯文本内容
        StringBuilder sb = new StringBuilder();
        //存储图片
        List<String> images = new ArrayList<>();

        List<Map> contentList = JSONArray.parseArray(content, Map.class);
        for (Map map : contentList) {
            if (map.get("type").equals("text")) {
                sb.append(map.get("value"));
            }

            if (map.get("type").equals("image")) {
                images.add((String) map.get("value"));
            }
        }
//todo
        if (wmNews.getImages() != null && wmNews.getType() != 0) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", sb.toString());
        resultMap.put("images", images);
        return resultMap;
    }


    /**
     * 保存app文章相关的数据
     * @param wmNews
     */
    private void saveAppArticle(WmNews wmNews) {
//        保存app文章
        ApArticle article = saveArticle(wmNews);
//        保存app文件配置
        saveArticleConfig(article);
//        保存内容
        saveArticleContent(article,wmNews);
//        修改自媒体文章的状态为9
        updateWmNews(wmNews,(short)9,"审核通过");
        //todo es索引

    }

    /**
     * 修改文章状态
     * @param wmNews
     * @param status
     * @param msg
     */
    private void updateWmNews(WmNews wmNews, short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wemediaFeign.updateWmNews(wmNews);
    }

    /**
     * 保存文章文本
     * @param apArticle
     */
    private void saveArticleContent(ApArticle apArticle,WmNews wmNews) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        articleFeign.saveArticleContent(apArticleContent);
    }

    /**
     * 保存文章配置信息
     * @param apArticle
     */
    private void saveArticleConfig(ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsForward(true);

        articleFeign.saveArticleConfig(apArticleConfig);
    }

    /**
     * 保存App文章
     * @param wmNews
     * @return
     */
    private ApArticle saveArticle(WmNews wmNews) {
        ApArticle article = new ApArticle();
        // 设置标题
        article.setTitle(wmNews.getTitle());
        // 设置创建时间
        article.setCreatedTime(new Date());
        // 封面图片,多张由逗号分割
        article.setImages(wmNews.getImages());
        // 设置页面布局
        article.setLayout(wmNews.getType());

        // 获取作者相关信息
        Integer userId = wmNews.getUserId();
        // 查找自媒体用户
        WmUser wmUser = wemediaFeign.findWmUserById(userId.longValue());
        if (wmUser != null){
            String name = wmUser.getName();
            // 查找作者
            ApAuthor apAuthor = articleFeign.selectAuthorByName(name);
            if (apAuthor != null){
                // 设置作者Id
                article.setAuthorId(apAuthor.getId().longValue());
                // 设置作者名字
                article.setAuthorName(apAuthor.getName());
            }
        }
        // 获取频道信息
        Integer channelId = wmNews.getChannelId();
        AdChannel adChannel = adChannelMapper.selectById(channelId);
        if (adChannel != null){
            article.setChannelId(adChannel.getId());
            article.setChannelName(adChannel.getName());
        }
        return articleFeign.saveArticle(article);
    }

    @Override
    public PageResponseResult findNews(NewsAuthDto dto) {
        //分页查询
        PageResponseResult responseResult =  wemediaFeign.findList(dto);
        //有图片需要显示，需要fasfdfs服务器地址
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult findOne(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2查询数据
        WmNewsVo wmNewsVo = wemediaFeign.findWmNewsVo(id);
        //结构封装
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(Integer type, NewsAuthDto dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = wemediaFeign.findById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.审核没有通过
        if(type.equals(0)){
            updateWmNews(wmNews,(short)2,dto.getMsg());
        }else if(type.equals(1)){
            //4.人工审核通过
            updateWmNews(wmNews,(short)4,"人工审核通过");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
